import os
import sys

replace_orig_space = "[_space]" #word to replace replace_space 
replace_orig_tab = "[_tab]"     #word to replace replace_tab
replace_orig_linefeed = "[_lf]" #word to replace replace_linefeed

replace_space = "[space]"       #word to replace " "
replace_tab = "[tab]"           #word to replace "/t"
replace_linefeed = "[lf]"       #word to replace "/n"

#Print Usage
def PringUsage(info):

    print "Error: "
    print "  %s" % info
    print "Usage: "
    print "  python Ulpia_WhitespaceTranslator [-e|-d] [inputfile] [outputfile]"

#Encode file from inputpath to outputpath
def EncodeFile(inputpath, outputpath):

    inputfile = open(inputpath)
    text = inputfile.read()
    inputfile.close()

    text = text.replace(replace_space, replace_orig_space)
    text = text.replace(replace_tab, replace_orig_tab)
    text = text.replace(replace_linefeed, replace_orig_linefeed)

    text = text.replace(" ", replace_space)
    text = text.replace("\t", replace_tab)
    text = text.replace("\n", replace_linefeed)

    outputfile = open(outputpath, 'w')
    outputfile.write(text)
    outputfile.close()

    print "Encoding complete!"
    
#Decode file from inputpath to outputpath
def DecodeFile(inputpath, outputpath):
    
    inputfile = open(inputpath)
    text = inputfile.read()
    inputfile.close()

    text = text.replace(replace_space, " ")
    text = text.replace(replace_tab, "\t")
    text = text.replace(replace_linefeed, "\n")
    
    text = text.replace(replace_orig_space, replace_space)
    text = text.replace(replace_orig_tab, replace_tab)
    text = text.replace(replace_orig_linefeed, replace_linefeed)

    outputfile = open(outputpath, 'w')
    outputfile.write(text)
    outputfile.close()

    print "Decoding complete!"

#main
if __name__ == '__main__':

    print
    print "Ulpia_WhitespaceTranslator1.0 2015 Tsybius Lee"
    print "----------------------------------------"

    if len(sys.argv) != 4:
        PringUsage("Illegal input parameters")
        os._exit(1)

    script_path = sys.argv[0]
    manipulation = sys.argv[1]
    input_file = sys.argv[2]
    output_file = sys.argv[3]

    print "Script Path: ", sys.argv[0]
    print "Manipulation: ", sys.argv[1]
    print "Input File: ", sys.argv[2]
    print "Output File: ", sys.argv[3]
    
    print "----------------------------------------"

    if sys.argv[1] != "-e" and sys.argv[1] != "-d":
        PringUsage("Manipulation must be encode(-e) or decode(-d)")
        os._exit(1)

    if not os.path.exists(sys.argv[2]):
        PringUsage("File %s does not exist!" % sys.argv[2])
        os._exit(1)

    if sys.argv[1] == "-e":
        EncodeFile(sys.argv[2], sys.argv[3])
    else:
        DecodeFile(sys.argv[2], sys.argv[3])
    
        
